package com.gitee.yunduansing.authcommon.filter;

import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import cn.hutool.json.JSONUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.gitee.yunduansing.authcommon.model.common.ResponseModel;

import java.io.IOException;

public class HttpStatusLoginFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest
            , HttpServletResponse response
            , AuthenticationException e) throws IOException, ServletException {
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setHeader("Content-Type", "application/json");
        var stream=response.getOutputStream();
        stream.println(JSONUtil.toJsonStr(ResponseModel.error(HttpStatus.UNAUTHORIZED.value(),e.getLocalizedMessage())));
        stream.close();
    }
}
